package com.dmw.config;

import com.dmw.filter.JwtAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                // 启用默认CORS配置
                .cors(cors -> cors.configure(http))
                //禁用csrf,后期可设置csrf令牌等
                .csrf(csrf -> csrf.disable())
                //会话管理
                .sessionManagement(sm -> sm
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                )
                //授权请求配置
                .authorizeHttpRequests(auth -> auth
                        //匹配登录和注册请求并且设置访问权限，对所有用用户可用
                        .requestMatchers("/user/login", "/user/register").permitAll()
                        //匹配接口文档请求并设置对所有用户可用
                        .requestMatchers("/v3/api-docs/**", "/swagger-ui/**").permitAll()

                        //测试角色访问
                        .requestMatchers("/api/user").hasRole("user")
                        .requestMatchers("/api/admin/**").hasRole("admin")
                        //所有未被前面规则匹配的请求，都需要用户进行身份验证才能访问
                        .anyRequest().authenticated()
                )
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                .build();
    }
    //注册Bcrypt的bean
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}